#include "client_item_base.h"

#include <sys/socket.h>
#include <errno.h>


namespace tinySrv
{  
 
  ClientItemBase::ClientItemBase()
    : MarkedForClose(false)
    , Socket(-1)
  {
  }
  
  ClientItemBase::~ClientItemBase()
  {
    if (!User.get())
      return;
    User->Done();
  }
  
  void ClientItemBase::MarkForClose()
  {
    MarkedForClose = true;
  }
   
  bool ClientItemBase::CanClose() const
  {
    return MarkedForClose;
  }
  
  void ClientItemBase::SetSocket(int sock)
  {
    Socket = sock;
  }
  
  int ClientItemBase::GetSocket() const
  {
    return Socket;
  }
  
  void ClientItemBase::SetUser(std::auto_ptr<IClient> user)
  {
    User = user;
  }
  
  void ClientItemBase::OnClose()
  {
    if (!User.get())
      return;
    User->OnClose();
  }
  
  void ClientItemBase::OnData(void const *data, int bytes)
  {
    if (!User.get())
      return;
    User->OnData(data, bytes);
  }
  
  void ClientItemBase::CloseMe()
  {
    MarkForClose();
  }
  
  bool ClientItemBase::SendData(void const *data, int *bytes)
  {
    int Res = send(Socket, data, *bytes, 0);
    if (Res == -1)
    {
      *bytes = 0;
      return errno == EWOULDBLOCK;
    }
    *bytes = Res;
    return true;
  }
    
}
